import { createRouter, createWebHistory } from 'vue-router'
import { getWebsiteName } from "@/utils/auth"
import { useTitle } from "@vueuse/core"
import { useUserStore } from "@/pinia"
import { broadcastEmitter } from "@/utils/emitter"
import { mobile } from "@/utils/tools"

export const route = [
    {
        path: '/',
        name: 'Index',
        meta: {
            title: '首页',
            header: true,
            icon: 'blog-icon-home',
            login: false
        },
        component: () => import('@/views/Index/Index')
    },
    {
        path: '/note',
        name: 'Note',
        meta: {
            title: '笔记',
            header: true,
            icon: 'blog-icon-biji',
            login: false
        },
        component: () => import('@/views/Note/Note')
    },
    {
        path: '/api',
        name: 'Api',
        meta: {
            title: 'Api列表',
            icon: 'blog-icon-waibujiekou',
            header: true,
            login: false
        },
        component: () => import('@/views/Api/Api')
    },
    {
        path: '/collect',
        name: 'Collect',
        meta: {
            title: '网站收藏',
            icon: "blog-icon-shoucangjia",
            header: true,
            login: false
        },
        component: () => import('@/views/Collect/Collect')
    }, {
        path: '/about',
        name: 'About',
        meta: {
            title: '简介',
            icon: "blog-icon-xinxi",
            header: true,
            login: false
        },
        component: () => import('@/views/About/About')
    },
    {
        path: '/user',
        name: 'User',
        meta: {
            title: '用户中心',
            icon: "blog-icon-shoucang",
            header: true,
            login: true,
            mobile: false
        },
        component: () => import('@/views/User/UserInfo')
    },
    {
        path: '/note/detail',
        name: 'NoteDetail',
        meta: {
            title: '笔记详情',
            login: false
        },
        component: () => import('@/views/Note/Detail')
    },
    {
        path: '/:catchAll(.*)',
        meta: {
            default: true,
            login: false
        },
        redirect: "/"
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: route.filter(e => e.meta.mobile === undefined ? true : e.meta.mobile === mobile)
})

router.beforeEach((to, from) => {
    if (to.meta.login && !useUserStore().islogin) {
        broadcastEmitter("login")
        if (from.path === '/' && !from.matched.length) {
            return "/"
        }
        return false
    }
    const websiteName = getWebsiteName();
    useTitle((to.meta.title || to.name) + (websiteName ? " | " + websiteName : ""))
})

export default router
